package cn.itcast.vector;

import jakarta.annotation.PostConstruct;
import org.springframework.ai.document.Document;
import org.springframework.ai.vectorstore.VectorStore;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 套餐规则向量库初始化：项目启动时将规则写入SimpleVectorStore
 */
@Component
public class RuleVectorStoreInitializer {
    private static final Logger logger = LoggerFactory.getLogger(RuleVectorStoreInitializer.class);

    // 注入配置好的内存向量库（SimpleVectorStore）
    @Autowired
    private VectorStore vectorStore;

    /**
     * @PostConstruct：项目启动后自动执行，加载规则到向量库
     */
    @PostConstruct
    public void initRuleVectorStore() {
        try {
            List<Map<String, String>> ruleList = createRuleList();
            List<Document> ruleDocuments = convertToDocuments(ruleList);
            vectorStore.add(ruleDocuments);
            logger.info("套餐规则已成功加载到内存向量库，共{}条规则", ruleDocuments.size());
        } catch (Exception e) {
            logger.error("初始化向量库规则失败", e);
        }
    }

    /**
     * 创建规则列表
     * @return 规则列表
     */
    private List<Map<String, String>> createRuleList() {
        List<Map<String, String>> ruleList = new ArrayList<>();
        
        // rule_01：合约期违约金规则
        Map<String, String> rule01 = new HashMap<>();
        rule01.put("ruleId", "rule_01");
        rule01.put("type", "合约期");
        rule01.put("condition", "合约期未满12个月");
        rule01.put("description", "提前更换套餐需支付剩余费用的10%作为违约金。");
        ruleList.add(rule01);

        // rule_02：携号转网规则
        Map<String, String> rule02 = new HashMap<>();
        rule02.put("ruleId", "rule_02");
        rule02.put("type", "携号转网");
        rule02.put("condition", "申请携号转网");
        rule02.put("description", "需满足：1. 无欠费 2. 当前套餐已到期 3. 非吉祥号段（如138/139开头）。");
        ruleList.add(rule02);
        
        return ruleList;
    }

    /**
     * 将规则列表转换为Document对象列表
     * @param ruleList 规则列表
     * @return Document对象列表
     */
    private List<Document> convertToDocuments(List<Map<String, String>> ruleList) {
        List<Document> ruleDocuments = new ArrayList<>();
        for (Map<String, String> rule : ruleList) {
            String content = String.format(
                    "%s规则：条件-%s，描述-%s",
                    rule.get("type"),
                    rule.get("condition"),
                    rule.get("description")
            );

            // 存储规则ID/类型，方便后续回答时引用规则ID
            Map<String, Object> metadata = new HashMap<>();
            metadata.put("ruleId", rule.get("ruleId"));
            metadata.put("ruleType", rule.get("type"));

            // 创建Document并添加到列表
            ruleDocuments.add(new Document(content, metadata));
        }
        return ruleDocuments;
    }
}